package com.example.week02.day1.Activity;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;

import com.example.week02.R;
import com.example.week02.day1.Broadcast.MyDynamicReceiver;

//动态广播
public class SendBroadcast_2 extends AppCompatActivity {

    String myAction = "com.broadcast.dynamic";

    MyDynamicReceiver myDynamicReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_send_broadcast2);

        //注册广播
        registerBroadcastReceiver();
        findViewById(R.id.BCR2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendBroadcast(new Intent(myAction));
            }
        });
    }


    //动态广播注册 固定的几步
    private void registerBroadcastReceiver(){
        myDynamicReceiver = new MyDynamicReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(myAction);
        registerReceiver(myDynamicReceiver,intentFilter, RECEIVER_EXPORTED);
    }


    //注销动态广播 如不注销会导致内存泄露
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myDynamicReceiver);
    }
}